package examples.ejb.ejb20.basic.security;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import weblogic.ejbgen.*;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SecurityBean is a stateless Session Bean. This bean illustrates:
 * <ul>
 * <li> No persistence of state between calls to the Session Bean
 * <li> Looking up values from the Environment
 * </ul>
 *
 * @author Copyright (c) 1999-2008 by BEA Systems, Inc. All Rights Reserved.
 */
@EnvEntries({
    @EnvEntry(name = "WEBL",
              type = "java.lang.Double",
              value = "10.0"),
    @EnvEntry(name = "minLimit",
              type = "java.lang.Integer",
              value = "6"),
    @EnvEntry(name = "maxLimit",
              type = "java.lang.Integer",
              value = "15")
})
@FileGeneration(remoteClass = Constants.Bool.TRUE,
                localHome = Constants.Bool.FALSE,
                remoteHome = Constants.Bool.TRUE,
                remoteClassName = "Security",
                remoteHomeName = "SecurityHome",
                localClass = Constants.Bool.FALSE)
@JarSettings(ejbClientJar = "ejb20_basic_security_client.jar")
@JndiName(remote = "ejb20-security-SecurityHome")
@Session(maxBeansInFreePool = "1000",
         initialBeansInFreePool = "0",
         transTimeoutSeconds = "0",
         type = Session.SessionType.STATELESS,
         defaultTransaction = Constants.TransactionAttribute.REQUIRED,
         ejbName = "security",
         enableCallByReference = Constants.Bool.TRUE)
public class SecurityBean implements SessionBean {

  private static final boolean VERBOSE = false;
  private SessionContext ctx;
  private int minLimit;
  private int maxLimit;
  ///private static List<PasswordRec> listOfNames = new ArrayList<PasswordRec>();
  private static List<String[]> listOfNames = new ArrayList<String[]>();

//	private static class PasswordRec{
//		String username;
//		String password;
//		
//		PasswordRec (String username, String password){
//			this.username=username;
//			this.password=password;
//		}
//		
//		public String getUsername() {
//			return username;
//		}
//
//		public void setUsername(String username) {
//			this.username = username;
//		}
//		public String getPassword() {
//			return password;
//		}
//
//		public void setPassword(String password) {
//			this.password = password;
//		}
//		
//		public void print(){
//			System.out.printf("username: %s | password: %s\n",this.username,this.password);
//		}
//	}
	
  // You might also consider using WebLogic's log service
  private void log(String s) {
    if (VERBOSE) System.out.println(s);
  } 
  
  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbActivate() {
    log("ejbActivate called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbRemove() {
    log("ejbRemove called");
  }

  /**
   * This method is required by the EJB Specification,
   * but is not used by this example.
   *
   */
  public void ejbPassivate() {
    log("ejbPassivate called");
  }

  /**
   * Sets the session context.
   *
   * @param ctx               SessionContext Context for session
   */
  public void setSessionContext(SessionContext ctx) {
    log("setSessionContext called");
    this.ctx = ctx;
  }

  /**
   * This method corresponds to the create method in the home interface
   * "SecurityHome.java".
   * The parameter sets of the two methods are identical. When the client calls
   * <code>SecurityHome.create()</code>, the container allocates an instance of 
   * the EJBean and calls <code>ejbCreate()</code>.
   *
   * @exception               javax.ejb.CreateException if there is
   *                          a communications or systems failure
   * @see                     examples.ejb.ejb20.basic.statelessSession.Trader
   */
  public void ejbCreate () throws CreateException {
    log("ejbCreate called");

    try {
      InitialContext ic = new InitialContext();

      Integer tl = (Integer) ic.lookup("java:/comp/env/maxLimit");
      Integer t2 = (Integer) ic.lookup("java:/comp/env/minLimit");
    
      maxLimit = tl.intValue();
      minLimit = t2.intValue();
    } catch (NamingException ne) {
      throw new CreateException("Failed to find environment value "+ne);
    }
  }

  /**
   * Checks password against constraints
   *
   * @param password	      The password to check
   * @return                  True if the password is ok False otherwise
   *                          
   */
  @RemoteMethod()
  public boolean passesUIDConstraints(String uid) 
  {  
	    if (uid.length() > maxLimit || uid.length() < minLimit ) {
	        return(false);
	      }
	    return(true);
  }
  
  /**
   * Checks password against constraints
   *
   * @param password	      The password to check
   * @return                  True if the password is ok False otherwise
   *                          
   */
  @RemoteMethod()
  public boolean passesPasswordConstraints(String password) 
  {  
	    if (password.length() > maxLimit || password.length() < minLimit ) {
	        return(false);
	      }
	    return(true);
  }  
  
  /**
   * Buys shares of a stock for a named customer.
   *
   * @param stockSymbol       String Stock symbol
   * @param shares            int Number of shares to buy
   * @return                  TradeResult Trade Result
   *                          if there is an error while buying the shares
   */
  @RemoteMethod()
  public boolean authenticate(String uid, String password ) 
  {
	try {
		readTheFile();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}    
	for (String[] thisRec: listOfNames){
		if (thisRec[0].equals(uid) && thisRec[1].equals(password)) {
			return(true);
		}
	}
    return (false);
  }

	private static void readTheFile() throws FileNotFoundException {
		String line=null;
		Pattern extPattern=Pattern.compile("(\\w*)\\*(\\w*)\\*",Pattern.CASE_INSENSITIVE);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(
				new FileInputStream("C:/bea/wlserver_10.3/password.txt"))));	
		try {
			while ((line=reader.readLine())!=null){
				Matcher matcher = extPattern.matcher(line.trim());
				while (matcher.find()){
					String[] newRec = new String[2];
					newRec[0]= matcher.group(1);
					newRec[1]= matcher.group(2);
					//PasswordRec passwordRec = new PasswordRec(matcher.group(1),matcher.group(2));
					//listOfNames.add(passwordRec);
					listOfNames.add(newRec);
					///passwordRec.print();
				}
			}		
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}








